import pygame, script, player, operator, enemy
import math as Math
import tile_tools as tt
import projectile

class Map:
	def __init__(self,g,id):
		self.elist= []
		self.sign = {}
		self.tlist = []
		self.maparray = []
		self.blist = []
		self.poll = 0
		self.is_completed = False
		self.dx = 0
		self.dy = 0
		self.directory = "resources/map" + str(id)
		g.draw_loading_screen("Reading Map Files")
		self.reference = pygame.image.load(self.directory + "/map.bmp")
		tscript = script.Script(self.directory + "/tscript.txt")
		mscript = script.Script(self.directory + "/misc.txt")
		self.brain_trans = mscript.get_nvalue("BRAIN","int","=")
		pcolor = tscript.get_tuplevalue("P","int","=")
		bcolor = tscript.get_tuplevalue("B","int","=")
		self.bnum = tscript.get_nvalue("BNUM","int","=")
		tnum = tscript.get_nvalue("TNUM","int","=")
		self.tileset = pygame.image.load(self.directory + "/tileset1.bmp").convert()
		self.map_surface = pygame.Surface((self.reference.get_width()*32,self.reference.get_height()*32))
		self.bg_image = pygame.image.load( self.directory + "/"+ tscript.get_nvalue("BACKGROUND","string","=")).convert()
		g.draw_loading_screen("Retrieving tiles")
		self.enum = tscript.get_nvalue("ENUM","int","=")
		escript = script.Script("resources/map"+str(id)+"/ene.txt")
		ecol = []
		cnt = 0
		self.cursor_img = pygame.image.load("resources/graphics/target.png")
		self.cursor_img = tt.get_tile_graphic(0,32,32,self.cursor_img)
		self.brain_img = pygame.image.load("resources/graphics/brain.bmp")
		self.brain_img = tt.get_tile_graphic(0,32,32,self.brain_img)
		self.cfnt = pygame.font.Font("resources/menu/xfiles.ttf",15)
		self.wsurface = pygame.Surface((800,600))
		#self.cursor_img.set_colorkey((255,0,255))
		for i in range(0, self.enum+1):
			tmp_sum = escript.get_nvalue("E"+str(i)+"_NUM","int","=")
			strng = escript.get_nvalue("E"+str(i)+"_IMAGE","string","=")
			tmp_type = tscript.get_nvalue("E"+str(i)+"_TYPE","string","=")
			if strng <> None:
				eset = pygame.image.load(strng)
			for j in range(0,tmp_sum+1):
				if tmp_type == "lrgunner":
					tmp_enemy = enemy.lrgunner(id,cnt,0,0,eset,tscript.get_tuplevalue("E"+str(i),"int","="))
				if tmp_type == "moving_gunner":
					tmp_range = escript.get_nvalue("E"+str(i)+"_I"+str(j)+"_RANGE","int","=")
					tmp_enemy = enemy.moving_gunner(id,cnt,0,0,eset,tscript.get_tuplevalue("E"+str(i),"int","="),tmp_range)
				if tmp_type == "soldier":
					tmp_enemy = enemy.soldier(id,cnt,0,0,tscript.get_tuplevalue("E"+str(i),"int","="))
				self.elist.append(tmp_enemy)
				cnt = cnt + 1
		self.enum = cnt
		for i in range(0,tnum):
			tmp_list = []
			#Insert pygame tile
			tmp_list.append(tt.get_tile_graphic(i,32,32,self.tileset))
			tmp_list.append( tscript.get_tuplevalue("T"+str(i),"int","="))
			tmp_list.append( tscript.get_nvalue("T"+str(i)+"_TYPE","string","="))
			self.tlist.append(tmp_list)
		g.draw_loading_screen("Setting map")
		#self.map_surface.set_colorkey((255,0,255))
		for i in range(0, self.reference.get_height()):
			tmparray = []
			for j in range(0, self.reference.get_width()):
				tmparray.append(-1)
			self.maparray.append(tmparray)
		c = -1
		s = 0
		t = 0
		signcol = (0,255,255)
		for i in range(0, self.reference.get_height()):
			for j in range(0, self.reference.get_width()):
				c = c + 1
				for m in range(0, self.enum):
					if self.reference.get_at((j,i)) == self.elist[m].col and self.elist[m].checked == 0:
						self.elist[m].x = j*32
						self.elist[m].y = i*32
						self.elist[m].checked = 1
						break
				
				for k in range(0, tnum):
					tmp = self.tlist[k]
					if self.reference.get_at((j,i)) == bcolor:
						tmpb = Brain_Obj(j*32,i*32,bcolor)
						self.blist.append(tmpb)
					if self.reference.get_at((j,i)) == pcolor:
						self.d_plyx = j*32
						self.d_plyy = i*32
						self.ply = player.Player(self.d_plyx,self.d_plyy)
					if self.reference.get_at((j,i)) == tmp[1]:
						self.maparray[i][j] = k
						t = k
				if self.reference.get_at((j,i)) == signcol:
					tmp_sign = Sign(c,mscript.get_nvalue("SIGN"+str(s),"string","="))
					self.sign[j*self.reference.get_width() - self.reference.get_width() - i] = tmp_sign
					#print s
					s = s + 1
		for i in range(0,self.bnum):
			self.blist[i].set_trans(mscript.get_nvalue("BRAIN"+str(i),"int","="))
	
	def get_poll(self,poll):
		self.poll = poll
	
	def set_poll(self):
		return self.poll
	
	def restart(self):
		self.ply.restart(self.d_plyx,self.d_plyy)
		self.dx = 0
		self.dy = 0
		self.is_completed = 0
		for i in range(0,self.enum):
			self.elist[i].health = 100
	
	def get_time(self,t):
		self.time = t
	
	def scroll(self):
		#Further left
		#if self.dx  0:
		#if self.ply.MoveBits[1] == 1:
		if self.dx < 0:
			self.dx = self.dx + self.ply.v
		if self.dx <= self.reference.get_width() * 32 or self.ply.MoveBits[1] == 1:
			if self.ply.x - self.dx >= (800/2):
				self.dx = self.dx + self.ply.v
		#elif self.ply.MoveBits[0] == 1:
		if self.dx >= 0 or self.ply.MoveBits[0] == 1:
			if self.ply.x - self.dx + 2 < (800/2):
				self.dx = self.dx - self.ply.v
		if self.ply.falling == True and self.ply.jump_force == 0:
			if self.dy <= self.reference.get_height() * 32:
				if self.ply.y + self.dy > (600/2):
					self.dy = self.dy - self.ply.v*self.ply.g
		#elif self.ply.MoveBits[2] == 1 or self.ply.jump_force > 0:
		if self.dy <= 0:
			if self.ply.y + self.dy <= (600/2):
				self.dy = self.dy + self.ply.jump_force
		if self.dy > 0:
			self.dy = 0
	
	def draw_win_screen(self,g):
		if pygame.key.get_pressed()[pygame.K_SPACE] == False:
			if g.level_status[g.curmap] == 2:
				status_surface = self.cfnt.render("LEVEL 1 REVISTED COMPLEYED",True,(255,0,0))
			else:
				status_surface = self.cfnt.render("LEVEL 1 COMPLETED",True,(255,0,0))
			self.wsurface.blit(status_surface,(0,0))
			points_surface = self.cfnt.render("POINTS:",True,(255,0,0))
			self.wsurface.blit(points_surface,(0,100))
			pointsn_surface = self.cfnt.render(str(self.ply.points),True,(255,0,0))
			self.wsurface.blit(pointsn_surface,(100,100))
			unlock_level_surf = self.cfnt.render("LEVEL UNLOCKED:",True,(0,0,255))
			self.wsurface.blit(unlock_level_surf,(0,200))
			unlock_leveln_surf = self.cfnt.render(str(self.nxt_lvl),True,(0,0,255))
			self.wsurface.blit(unlock_leveln_surf,(300,200))
			message = self.cfnt.render("PRESS SPACE TO CONTINUE",True,(0,0,255))
			self.wsurface.blit(message,(0, 400))
			return self.wsurface
		else:
			g.level_status[g.curmap] = 2
			g.level_status[self.nxt_lvl] = 1
			self.restart()
			g.mode = 2
			return self.wsurface
	
	def draw(self,g):
		if self.is_completed == True:
			self.map_surface.blit(self.draw_win_screen(g),(0,0))
			return self.map_surface
		self.map_surface.blit(self.bg_image,(0,0))
		self.scroll()
		c = 0
		xrange = int(Math.floor(self.dx/32))
		yrange = abs(int(Math.floor(self.dy/32)))
		for i in range(yrange,yrange+20):
			for j in range(xrange, xrange+26):
				if i >= self.reference.get_height() or j >= self.reference.get_width():
					break;
				v = self.maparray[i][j]
				if v is not -1:
					tmp = self.tlist[self.maparray[i][j]]
					self.map_surface.blit(tmp[0],((j*32) - self.dx,(i*32)+self.dy))
				c = c + 1
		self.ply.move_player(self.dx,self.dy,self)
		col = self.ply.check_col2(self,self.reference.get_width(),self.reference.get_height(),32,64)
		#Draw player projectiles
		for proj in self.ply.plist:
			tmpdraw = proj.draw()
			self.map_surface.blit(tmpdraw,(proj.x-self.dx,proj.y+self.dy))
		#Draw player
		self.map_surface.blit(self.ply.draw(),(self.ply.x - self.dx,self.ply.y+self.dy))
		#Draw enemies
		for i in range(0, self.enum):
			if self.elist[i].x + self.elist[i].w >= self.dx and self.elist[i].x+ self.elist[i].w <= self.dx + 800 and self.elist[i].y+ self.elist[i].h >= abs(self.dy) and self.elist[i].y+ self.elist[i].h <= abs(self.dy) + 600 :
				if self.elist[i].is_dead(self.ply) == False:
					self.map_surface.blit(self.elist[i].draw(self.ply),(self.elist[i].x-self.dx,self.elist[i].y+self.dy))
					if self.elist[i].is_dead(self.ply) == False:
						self.elist[i].collide_player(self.ply)
						self.elist[i].shoot(self,self.time,20,self.ply)
						#Draw enemy projectile
						for proj in self.elist[i].plist:
							if proj.x >= self.dx and proj.x <= self.dx + 800 and proj.y >= abs(self.dy) and proj.y <= abs(self.dy) + 600 :
								tmpdraw = proj.draw()
								self.map_surface.blit(tmpdraw,(proj.x-self.dx,proj.y+self.dy))
						#Draw Health
						self.map_surface.blit(self.elist[i].draw_health_bar(),(self.elist[i].x-self.dx,self.elist[i].y+self.dy-10))
		#Draw HUD Area
		self.map_surface.blit(self.ply.draw_hud_area(),(10,10))
		#Sign
		if col[0] == 2:
			self.map_surface.blit(self.sign[col[2]*self.reference.get_width() - self.reference.get_width() - col[1]].draw_txt(),(self.ply.x-self.dx,self.ply.y - 20 + self.dy))
		#Draw brain objective
		for i in range(0, self.bnum):
			self.map_surface.blit(self.brain_img,(self.blist[i].x-self.dx,self.blist[i].y+self.dy))
		#Healing pack
		if col[0] == 3:
			self.ply.heal(20)
			self.maparray[col[1]][col[2]] = -1
		#Get objective
		if col[0] == 4:
			if g.level_status[g.curmap] == 2:
				g.global_points += int(self.ply.points*0.1)
			else:
				g.global_points += self.ply.points
			self.nxt_lvl = self.blist[col[1]].n
			self.is_completed = True

		if col[0] == 5:
			self.ply.acid_num += 20
			self.maparray[col[1]][col[2]] = -1
		if self.ply.is_dead() == True:
			self.restart()
		self.map_surface.blit(self.cursor_img,(self.ply.aimx,self.ply.aimy))
		return self.map_surface
				
	def del_surface(self):
		self.map_surface.fill((0,0,0))
		
class Brain_Obj:
	def __init__(self,x,y,col):
		self.x = x
		self.y = y
		self.col = col
	
	def set_trans(self, n):
		self.n = n
		
class Sign:
	def __init__(self,id,txt):
		self.id = id
		self.txt = txt
		self.fnt = pygame.font.Font("resources/menu/xfiles.ttf",15)
	
	def draw_txt(self):
		txt_surface = self.fnt.render(self.txt,True,(0,255,0))
		return txt_surface
		
		